<!--
 * @author wangpeizhi
 -->
<template>
  <div class="lottery-manage">
    <div class="lottery-manage-title">新建/编辑抽奖活动</div>
    <section v-loading="loading" class="lottery-manage-main">
      <el-form ref="form" :model="form" :rules="rules" label-width="240px" label-position="center" class="form">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model.trim="form.activityName" />
        </el-form-item>
        <el-form-item label="活动图片" prop="activityImg">
          <image-upload
            :key="uploadFile.imagecropperKey"
            v-model="form.activityImg"
            :preview-id="uploadFile.viewId"
            :is-oss="isOss"
            :forever="true"
            :width="750"
            :view="uploadFile.view"
            :height="330"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item>
        <!-- <el-form-item label="活动背景图" prop="activityBackgroundImg">
          <image-upload
            :key="uploadFile.imagecropperKey"
            v-model="form.activityBackgroundImg"
            :preview-id="form.activityBackgroundImg"
            :forever="true"
            :width="750"
            :view="uploadFile.view"
            :height="330"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item>
        <el-form-item label="活动背景颜色" prop="activityBackgroundColor">
          <div class="block">
            <el-color-picker v-model="form.activityBackgroundColor" />
          </div>
        </el-form-item> -->
        <el-form-item label="开始日期" prop="activityStartTime">
          <el-date-picker
            v-model="form.activityStartTime"
            type="datetime"
            placeholder="选择开始日期"
            style="width: 100%"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="activityEndTime">
          <el-date-picker
            v-model="form.activityEndTime"
            type="datetime"
            placeholder="选择结束日期"
            style="width: 100%"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="兑换所需积分数量" prop="needIntegralNum">
          <el-input v-model.trim="form.needIntegralNum" />
        </el-form-item>
        <el-form-item label="每日可兑换次数" prop="exchangeDayNum">
          <el-input v-model.trim="form.exchangeDayNum" />
        </el-form-item>
        <el-form-item label="总兑换次数" prop="exchangeNum">
          <el-input v-model.trim="form.exchangeNum" style="width:87%" min="0" :disabled="exchangeNumCheck" />
          <el-checkbox v-model="exchangeNumCheck" label="不限制" style="width:10%" />
        </el-form-item>
        <el-form-item label="每日免费次数" prop="freeDayNum">
          <el-input v-model.trim="form.freeDayNum" />
        </el-form-item>
        <el-form-item label="总免费次数" prop="freeTotalNum">
          <el-input v-model.trim="form.freeTotalNum" min="0" style="width:87%" :disabled="freeTotalNumCheck" />
          <el-checkbox v-model="freeTotalNumCheck" label="不限制" style="width:10%" />
        </el-form-item>
        <el-form-item label="抽奖配置" prop="bigturntableId">
          <div>
            <el-button class="button-new-tag" size="small" @click="showInputRwys">抽奖配置</el-button>
          </div>
          <div>
            <el-tag v-if="dialogMultipleSelections.bigturntableName" closable @close="handleCloses(dialogMultipleSelections)">
              {{ dialogMultipleSelections.bigturntableName || bigturntableName }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="活动规则" prop="activityExplain">
          <!-- <el-input
            v-model.trim="form.activityExplain"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea"
            placeholder="请输入活动说明"
          /> -->
          <el-input
            v-model="form.activityExplain"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            maxlength="500"
            placeholder="请输入抽奖说明"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序号（值越大，越靠前）" />
        </el-form-item>
      </el-form>
    </section>

    <section class="lottery-manage-footer">
      <el-button style="padding: 10px 30px" @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleComit('form')">确 定</el-button>
    </section>
    <!-- 选择转盘 -->
    <el-dialog title="选择抽奖配置" :visible.sync="dialogFormVisibles" center fullscreen :close-on-click-modal="false">
      <add-prize
        v-if="dialogFormVisibles"
        ref="resetAll"
        v-loading.fullscreen.lock="fullscreenLoadings"
        :before-list="beforeLists"
        :bigturntable-id="form.bigturntableId"
        @userData="userDatas"
      />
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px" @click="dialogFormVisibles = false">取消</el-button>
        <el-button style="padding: 8px 30px" type="primary" @click="insertUsers()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import ImageUpload from '@/components/ImageUpload'
import { specialText } from '@/utils/validate'
import { insertDraw, get, update } from '../api/index'
import addPrize from '../components/addPrize.vue'
export default {
  name: 'LotteryManage',
  components: { ImageUpload, addPrize },
  data() {
    var checkEnd = (rule, value, callback) => {
      if (this.form.startTime === '') {
        callback(new Error('请选择开始日期'))
      } else {
        if (new Date(this.form.startTime).getTime() > new Date(value).getTime()) {
          callback(new Error('结束日期不能早于开始日期'))
        }
        callback()
      }
    }
    return {
      isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false,
      beforeLists: [],
      dialogMultipleSelections: {},
      fullscreenLoadings: false,
      dialogFormVisibles: false,
      loading: false,
      exchangeNumCheck: false,
      freeTotalNumCheck: false,
      form: {
        activityName: '',
        activityStartTime: '',
        activityEndTime: '',
        activityImg: '', // 活动图片
        // activityBackgroundImg: '', // 活动背景图
        // activityBackgroundColor: '', // 活动背景颜色
        activityExplain: '', // 活动说明
        bigturntableId: '', // 大转盘ID
        needIntegralNum: '', // 兑换所需积分数量
        exchangeNum: '', // 可兑换次数
        exchangeDayNum: '', // 每日可兑换次数
        freeDayNum: '', // 可兑换次数
        freeTotalNum: '', // 可兑换次数
        sort: '' // 排序
      },
      bigturntableName: '',
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: false,
        accept: '',
        fileType: '',
        fileIndex: 0
      },
      rules: {
        activityName: [
          {
            required: true,
            message: '请输入活动名称',
            trigger: 'blur'
          }
        ],
        // activityImg: [
        //   {
        //     required: true,
        //     message: '请选择活动图片',
        //     trigger: 'blur'
        //   }
        // ],
        // activityBackgroundImg: [
        //   {
        //     required: true,
        //     message: "请选择活动背景图片",
        //     trigger: "blur",
        //   },
        // ],
        // activityBackgroundColor: [
        //   {
        //     required: true,
        //     message: "请输入活动背景颜色",
        //     trigger: "blur",
        //   },
        // ],
        activityExplain: [
          {
            required: true,
            message: '请输入活动说明',
            trigger: 'blur'
          }
        ],
        needIntegralNum: [
          {
            required: true,
            message: '请输入兑换所需积分数量',
            trigger: 'blur'
          }
        ],
        exchangeDayNum: [
          {
            required: true,
            message: '请输入每日可兑换次数',
            trigger: 'blur'
          }
        ],
        exchangeNum: [
          {
            required: true,
            message: '请输入总兑换次数',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.exchangeNumCheck || value !== '') {
                callback()
              } else if (!this.exchangeNumCheck && value === '') {
                callback(new Error('请输入总兑换次数'))
              }
            }
          }
        ],
        freeDayNum: [
          {
            required: true,
            message: '请输入每日免费次数',
            trigger: 'blur'
          }
        ],
        freeTotalNum: [
          {
            required: true,
            message: '请输入总免费次数',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.freeTotalNumCheck || value !== '') {
                callback()
              } else if (!this.freeTotalNumCheck && value === '') {
                callback(new Error('请输入总免费次数'))
              }
            }
          }
        ],
        bigturntableId: [
          {
            required: true,
            message: '请关联抽奖配置',
            trigger: 'blur'
          }
        ],
        sort: [
          {
            required: true,
            message: '请输入排序',
            trigger: 'blur'
          }
        ],
        activityStartTime: [
          {
            required: true,
            message: '请选择开始日期',
            trigger: 'change'
          }
        ],
        activityEndTime: [
          {
            required: true,
            message: '请选择结束日期',
            trigger: 'change'
          },
          {
            required: true,
            validator: checkEnd,
            trigger: 'change'
          }
        ]
      },
      state: 'create',
      t: '0',
      dict: {
        BIGTSTATUS: [] // 状态
      }
    }
  },
  watch: {
    'exchangeNumCheck'(newVal) {
      if (newVal) {
        this.$refs['form'].clearValidate(['exchangeNum'])
      }
    },
    'freeTotalNumCheck'(newVal) {
      if (newVal) {
        this.$refs['form'].clearValidate(['freeTotalNum'])
      }
    },
    'form.bigturntableId'(newVal) {
      if (newVal) {
        this.$refs['form'].clearValidate(['bigturntableId'])
      }
    }
  },
  created() {
    this.state = this.$route.query.type === 'c' ? 'create' : 'update'
    for (const key in this.dict) {
      // this.getDict(key)
    }
    if (this.$route.query.type === 'u') {
      if (this.$route.query.i) {
        this.getData(this.$route.query.i)
      } else {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    }
  },
  methods: {
    // 选择人物元素
    userDatas(val) {
      this.dialogMultipleSelections = Object.assign({}, val)
    },
    // 选择选择导师
    showInputRwys() {
      this.dialogFormVisibles = true
    },
    // 确定选择抽奖配置
    insertUsers() {
      console.log('111111', this.dialogMultipleSelections)
      if (JSON.stringify(this.dialogMultipleSelections) === '{}') {
        this.$message({
          message: '请选择抽奖配置',
          type: 'warning'
        })
      } else {
        this.$set(this.form, 'bigturntableId', this.dialogMultipleSelections.id)
        this.dialogListLoadings = true
        this.dialogFormVisibles = false
      }
    },
    // 选择转盘
    showInputRwys() {
      this.dialogFormVisibles = true
    },
    // 删除转盘
    handleCloses(dialogMultipleSelections) {
      this.dialogMultipleSelections.bigturntableName = null
      this.form.bigturntableId = ''
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.dict[code] = res.data.data && res.data.data.length > 0 ? res.data.data[0].list : []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    /**
     * 根编辑回显
     */
    getData() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({
          id: this.$route.query.i
        })
          .then((res) => {
            loading.close()
            this.bigturntableName = res.data.data.bigturntableName
            const data = res.data.data
            for (const key in this.form) {
              if (key === 'exchangeNum') {
                this.form[key] = data[key] === -1 ? '' : data[key]
                this.exchangeNumCheck = data[key] === -1
              } else if (key === 'freeTotalNum') {
                this.form[key] = data[key] === -1 ? '' : data[key]
                this.freeTotalNumCheck = data[key] === -1
              } else if (key === 'activityImg') {
                this.uploadFile.viewId = this.isOss ? data.activityImgURL : data.activityImg
                this.form.activityImg = data.activityImg
              } else if (key === 'bigturntableId') {
                this.dialogMultipleSelections = {
                  bigturntableName: data['bigturntableName'],
                  bigturntableId: data['bigturntableId']
                }
              } else {
                this.form[key] = data[key]
              }
            }
            this.form.bigturntableId = data.bigturntableId
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },

    /**
     * 取消
     */
    handleCancel() {
      this.$router.push({
        path: this.$filterPath('index'),
        query: {
          t: this.t
        }
      })
    },

    handleComit() {
      // console.log(this.form)
      // return
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form, {
              exchangeNum: !this.exchangeNumCheck ? this.form.exchangeNum : '-1',
              freeTotalNum: !this.freeTotalNumCheck ? this.form.freeTotalNum : '-1'
            })
            // params['']
            return new Promise((resolve, reject) => {
              insertDraw(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({
                    path: this.$filterPath('index')
                  })
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form, {
              exchangeNum: !this.exchangeNumCheck ? this.form.exchangeNum : '-1',
              freeTotalNum: !this.freeTotalNumCheck ? this.form.freeTotalNum : '-1'
            })
            params['id'] = this.$route.query.i
            return new Promise((resolve, reject) => {
              update(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({
                    path: this.$filterPath('index')
                  })
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            return false
          }
        })
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
@import '@/styles/mixin.scss';

.lottery-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .lottery-manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .lottery-manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px;
      /*对垂直流动条有效*/
      height: 1px;
      /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }

    .form {
      width: 1000px !important;
      margin: 0 auto;

      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }

    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;

      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }

    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
    }
  }

  .lottery-manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
<style lang="scss">
@import '@/styles/mixin.scss';

.lottery-manage {
  .classify-tree-con {
    position: relative;
    height: 400px;
    overflow: hidden;

    .classify-tree-con-scrollbar {
      overflow: hidden;

      .el-scrollbar__wrap {
        max-height: 381px;
      }
    }

    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      width: 100%;

      .tree-node-txt {
        flex: 1;
      }
    }
  }
}
</style>
